package controllers;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;

import utils.ImageProcessing;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class ImageController
 */
public class ImageController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ImageController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		String message = "";
		synchronized (session) {
			String user = (String) session.getAttribute("user");

			try {
				boolean isMultipart = ServletFileUpload
						.isMultipartContent(request);

				if (request.getParameter("deleteImage") != null) {
					String userImg = request.getParameter("deleteImage");
					String path = this.getServletContext().getRealPath(
							"/etc/img");
					File uploadedFile = new File(path + "/img_" + user + ".jpg");
					File profileFile = new File(path + "/profile_" + user
							+ ".jpg");
					File tweetFile = new File(path + "/tweet_" + user + ".jpg");

					uploadedFile.delete();
					profileFile.delete();
					tweetFile.delete();

				} else {
					if (isMultipart) {

						// Create a factory for disk-based file items
						FileItemFactory factory = new DiskFileItemFactory();
						// Create a new file upload handler
						ServletFileUpload upload = new ServletFileUpload(
								factory);
						// Parse the request
						List /* FileItem */items = upload.parseRequest(request);

						// Process the uploaded items
						Iterator iter = items.iterator();
						while (iter.hasNext()) {
							FileItem item = (FileItem) iter.next();

							if (item.isFormField()) {
								// error?
							} else {
								String contentType = item.getContentType();
								if (!contentType.startsWith("image")) {
									// Error: not image.
								} else {

									String path = this.getServletContext()
											.getRealPath("/etc/img");
									File uploadedFile = new File(path + "/img_"
											+ user + ".jpg");
									File profileFile = new File(path
											+ "/profile_" + user + ".jpg");
									File tweetFile = new File(path + "/tweet_"
											+ user + ".jpg");
									item.write(uploadedFile);

									BufferedImage sourceImage = ImageIO
											.read(uploadedFile);

									BufferedImage profileImg = ImageProcessing
											.createResizedCopy(sourceImage,
													150, 150, true);
									BufferedImage tweetImg = ImageProcessing
											.createResizedCopy(sourceImage, 60,
													60, true);

									ImageIO.write(profileImg, "jpeg",
											profileFile);
									ImageIO.write(tweetImg, "jpeg", tweetFile);
								}
							}
						}
					}

				}

			} catch (Exception ex) {
				ex.printStackTrace();
				message += "Ha habido un error al procesar la imagen.";
			}

			request.setAttribute("message", message);
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("HomeController");
			if (dispatcher != null)
				dispatcher.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
